package utils;

import book.PairOfUidAndBookId;
import com.bit.utils.FileUtils;
import constant.Constant;

import java.io.IOException;

public class AnalyzingBorrowedBook {
    public PairOfUidAndBookId[] loadUserIDAndBookId(String filename)throws IOException{
        PairOfUidAndBookId[] pairOfUidAndBookIds = new PairOfUidAndBookId[Constant.CAPACITY];
        String contents = FileUtils.readFile(filename);
        if(contents == null || contents.isEmpty()){
            return null;
        }
        String[] strings = contents.split("\n");

        if(strings.length >= pairOfUidAndBookIds.length){
            pairOfUidAndBookIds = new PairOfUidAndBookId[strings.length*2];
            System.out.println("扩容成功");
        }

        for (int i = 0; i < strings.length; i++) {
            String[] partS = strings[i].split(",");
            PairOfUidAndBookId pairOfUidAndBookId = new PairOfUidAndBookId();
            pairOfUidAndBookId.setUserId(Integer.parseInt(partS[0]));
            pairOfUidAndBookId.setBookId(Integer.parseInt(partS[1]));
            pairOfUidAndBookIds[i] = pairOfUidAndBookId;
        }

        return pairOfUidAndBookIds;
    }

    public void storeUserIDAndBookId(PairOfUidAndBookId[] pairOfUidAndBookIds, String filename) throws IOException{
        int useLen = 0;
        for (int i = 0; i < pairOfUidAndBookIds.length; i++) {
            if(pairOfUidAndBookIds[i] != null){
                useLen++;
            }
        }

        StringBuilder jsonArray = new StringBuilder();
        for (int i = 0; i < useLen; i++) {
            jsonArray.append(pairOfUidAndBookIds[i].json());
            if(i != pairOfUidAndBookIds.length-1){
                jsonArray.append("\n");
            }
        }

        FileUtils.writeFile(jsonArray.toString(), filename);
    }

    public static void main(String[] args) {
        AnalyzingBorrowedBook analyzingBorrowedBook = new AnalyzingBorrowedBook();
        PairOfUidAndBookId[] pairOfUidAndBookIds = new PairOfUidAndBookId[5];
        pairOfUidAndBookIds[0] = new PairOfUidAndBookId(2, 101);
        pairOfUidAndBookIds[1] = new PairOfUidAndBookId(3, 102);
        try {
            analyzingBorrowedBook.storeUserIDAndBookId(pairOfUidAndBookIds, Constant.BORROWED_BOOK_UID_BOOK_ID);
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}
